package com.hzsxy.bighomework.controller;

import com.hzsxy.bighomework.api.QuestionView;
import com.hzsxy.bighomework.api.SaveChoiceRequest;
import com.hzsxy.bighomework.api.SaveDesignRequest;
import com.hzsxy.bighomework.entity.*;
import com.hzsxy.bighomework.repository.*;
import com.hzsxy.bighomework.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class QuestionController {
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private ClassInfoRepository classInfoRepository;
    @Autowired
    private ChoiceRepository choiceRepository;
    @Autowired
    private DesignRepository designRepository;
    @Autowired
    private HomeworkRepository homeworkRepository;

    @RequestMapping("/questions")
    public String returnQuestionpage(Model model,HttpSession httpSession){
        String type = (String) httpSession.getAttribute("type");
        Teacher teacher = (Teacher) httpSession.getAttribute("info");
        List<QuestionView> questions = questionService.getAllQuestion(type,teacher.getName());
        model.addAttribute("questions",questions);
        return "teacher/question-management";
    }

    @RequestMapping("/questionsTotal")
    public String returnQuestionpageTotal(Model model,HttpSession httpSession){
        String type = (String) httpSession.getAttribute("type");
        Teacher teacher = (Teacher) httpSession.getAttribute("info");
        List<QuestionView> questions = questionService.getAllQuestion(type,teacher.getName());
        model.addAttribute("questions",questions);
        return "teacher/question-Total";
    }


    @RequestMapping("/addquestion")
    public String returnAddQuestionpage(){
        return "teacher/question-add";
    }

    @RequestMapping(value = "/question/add",method = RequestMethod.POST)
    @ResponseBody
    public String addQuestion(HttpServletRequest httpServletRequest, HttpSession httpSession){
        String title=httpServletRequest.getParameter("title");
        String description=httpServletRequest.getParameter("description");
        String author = ((Teacher)httpSession.getAttribute("info")).getName();
        try {
            QuestionDO question=new QuestionDO(title,description,author);
            questionRepository.save(question);
            return "successful";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        } catch (Exception e){
            return "failed";
        }
    }

    @RequestMapping(value = "/question/delete",method = RequestMethod.POST)
    @ResponseBody
    public String deleteQuestion(HttpServletRequest httpServletRequest){
        int question_id = Integer.parseInt(httpServletRequest.getParameter("question_id"));

        try {
            questionRepository.delete(question_id);
            return "successful";
        }catch (Exception e){
            return "failed";
        }
    }

    @RequestMapping("/editquestion")
    public String returnEditQuestionpage(Model model,HttpSession httpSession,@RequestParam("question_id")String question_id){
        QuestionDO question =questionRepository.findOne(Integer.valueOf(question_id));
        model.addAttribute("question",question);
        return "teacher/question-edit";
    }

    @RequestMapping("/question/edit")
    @ResponseBody
    public String editQuestion(HttpServletRequest httpServletRequest,HttpSession httpSession){
        int question_id= Integer.parseInt(httpServletRequest.getParameter("question_id"));
        String title=httpServletRequest.getParameter("title");
        String description=httpServletRequest.getParameter("description");
        String author = ((Teacher)httpSession.getAttribute("info")).getName();
        try{
            QuestionDO question=questionRepository.findOne(question_id);
            question.setTitle(title);
            question.setDescription(description);
            question.setAuthor(author);
            questionRepository.save(question);
            return "successful";
        }catch (Exception e){
            return "failed";
        }
    }

    @RequestMapping("/addChoicePage")
    public String addChoicePage(Model model,@RequestParam int questionId){
        List<ChoiceDO> choiceDOList = choiceRepository.findByQuestionId(questionId);
        model.addAttribute("questionId",questionId);
        return "teacher/choice-add";
    }

    @RequestMapping("/getChoices")
    public String getChoices(Model model,@RequestParam int questionId,HttpSession httpSession){
        List<ChoiceDO> choiceDOList = choiceRepository.findByQuestionId(questionId);
        model.addAttribute("choices",choiceDOList);
        model.addAttribute("questionId",questionId);
        String type = (String) httpSession.getAttribute("type");
        if ("student".equals(type)){
            return "student/choicesPage";
        }else {
            return "teacher/choicesPage";
        }
    }

    @RequestMapping("/removeChoice")
    @ResponseBody
    public String removeChoice(@RequestParam int choiceId){
        try{
            choiceRepository.delete(choiceId);
            return "successful";
        }catch (Exception e){
            return "failed";
        }
    }

    @PostMapping("/addChoice")
    @ResponseBody
    public String addChoice(SaveChoiceRequest request){
        try {
            questionService.saveChoice(request.getQuestionId(),request.getChoiceInfo(),request.getOp1(),request.getOp2(),request.getOp3(),request.getOp4());
            return "successful";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        }catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }





    @RequestMapping("/addDesignPage")
    public String addDesignPage(Model model,@RequestParam int questionId){
        List<DesignDO> designDOList = designRepository.findByQuestionId(questionId);
        model.addAttribute("questionId",questionId);
        return "teacher/design-add";
    }

    @RequestMapping("/getDesigns")
    public String getDesigns(Model model,@RequestParam int questionId,HttpSession httpSession){
        List<DesignDO> designDOList = designRepository.findByQuestionId(questionId);
        model.addAttribute("designs",designDOList);
        model.addAttribute("questionId",questionId);
        String type = (String) httpSession.getAttribute("type");
        if ("student".equals(type)){
            return "student/designsPage";
        }else {
            return "teacher/designsPage";
        }
    }

    @RequestMapping("/removeDesign")
    @ResponseBody
    public String removeDesign(@RequestParam int designId){
        try{
            designRepository.delete(designId);
            return "successful";
        }catch (Exception e){
            return "failed";
        }
    }

    @PostMapping("/addDesign")
    @ResponseBody
    public String addDesign(SaveDesignRequest request){
        try {
            questionService.saveDesign(request.getQuestionId(),request.getDesignInfo());
            return "successful";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        }catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }


    @RequestMapping("/getPublishPage")
    public String getPublishPage(Model model,@RequestParam int questionId){
        List<ClassInfoDO> choiceDOList = classInfoRepository.findAll();
        model.addAttribute("classes",choiceDOList);
        model.addAttribute("questionId",questionId);
        return "teacher/publishPage";
    }

    @PostMapping("/publishHomework")
    @ResponseBody
    public String publishHomework(HttpServletRequest httpServletRequest){
        try {
            String name = httpServletRequest.getParameter("name");
            List<String> classIdList = Arrays.asList(httpServletRequest.getParameterValues("classIds[]"));
            int questionId = Integer.valueOf(httpServletRequest.getParameter("questionId"));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String publishTimeString = httpServletRequest.getParameter("publishTime");
            Date publishTime;
            if (StringUtils.isEmpty(publishTimeString)){
                publishTime = new Date();
            }else {
                publishTime =  simpleDateFormat.parse(publishTimeString);
            }
            Date endTime = simpleDateFormat.parse(httpServletRequest.getParameter("endTime"));
            List<HomeworkDO> homeworkDOList = classIdList.stream().map(it -> new HomeworkDO(it,questionId,publishTime,endTime,name)).collect(Collectors.toList());
            homeworkRepository.save(homeworkDOList);
            return "successful";
        } catch (RuntimeException ex){
            ex.printStackTrace();
            return ex.getMessage();
        }catch (Exception ex){
            ex.printStackTrace();
            return "failed";
        }
    }
}
